package com.ls.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ls.rbac.entity.RolePermission;
import com.ls.rbac.mapper.RolePermissionMapper;
import com.ls.rbac.service.IRolePermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
/**

 * @author liusheng
 * @since 2025--06--28
 */
@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission> implements IRolePermissionService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveRolePermissions(Integer roleId, List<Integer> permissionIds) {
        LambdaQueryWrapper<RolePermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RolePermission::getRoleId, roleId);
        this.remove(queryWrapper);
        if (permissionIds != null && !permissionIds.isEmpty()) {
            List<RolePermission> rolePermissionList = new ArrayList<>();
            for (Integer permissionId : permissionIds) {
                RolePermission rolePermission = new RolePermission();
                rolePermission.setRoleId(roleId);
                rolePermission.setPermissionId(permissionId);
                rolePermissionList.add(rolePermission);
            }
            return this.saveBatch(rolePermissionList);
        }
        return true;
    }

    @Override
    public void removeByRoleId(Integer roleId) {
        LambdaQueryWrapper<RolePermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RolePermission::getRoleId, roleId);
        this.remove(wrapper);
    }
}
